package com.kh.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.kh.reggie.common.Result;
import com.kh.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查是否登入，过滤未登录的
 */
@Slf4j
@WebFilter(filterName ="LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//    路径匹配，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        1.获取请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",request.getRequestURI());
//        不需要拦截的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"

        };


//        2.判定请求是否拦截
        boolean check = check(urls, requestURI);

//        3.不需要就放行
        if (check){
            filterChain.doFilter(request,response);
            log.info("放行请求：{}",request.getRequestURI());
            return;
        }
//        4.1需要则判断登录状态，已登录则放行
        if(request.getSession().getAttribute("employee")!=null){
//          由于请求属于同一个线程，利用ThreadLocal获取empId
            Long empId =(Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            log.info("用户已登录，用户ID：{}",request.getSession().getAttribute("employee"));
            return;
        }
//        4.2需要则判断移动端登录状态，已登录则放行
        if(request.getSession().getAttribute("user")!=null){
//          由于请求属于同一个线程，利用ThreadLocal获取empId
            Long userId =(Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            log.info("用户已登录，用户ID：{}",request.getSession().getAttribute("user"));
            return;
        }
//        5.未登录则放行，返回状态，输出流向前端响应数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOLOGIN")));



        return;
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
